package com.spring.security;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.authority.AuthorityUtils;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.social.security.SocialUser;
import org.springframework.social.security.SocialUserDetails;
import org.springframework.social.security.SocialUserDetailsService;
import org.springframework.stereotype.Component;

@Component
public class MyUserDetailsService implements UserDetailsService, SocialUserDetailsService {

    @Autowired
    private PasswordEncoder passwordEncoder;

    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        System.out.println("登录用户名：" + username);
        return getUserDetails(username);
    }

    //社交登录
    @Override
    public SocialUserDetails loadUserByUserId(String userId) throws UsernameNotFoundException {
        System.out.println("社交登录ID：" + userId);
        return getUserDetails(userId);
    }

    private SocialUser getUserDetails(String username) {
        //这里可以通过用户名去数据库查用户的密码和账号状态，权限。
        //这一步应该是放在注册那一步然后从数据库取密码，这里我们是模拟加密
        String password = passwordEncoder.encode("123456");
        System.out.println("加密后的密码：" + password);
        SocialUser admin = new SocialUser(username,
                password,
                true, true, true, true,
                AuthorityUtils.commaSeparatedStringToAuthorityList("admin"));
        return admin;
    }
}
